<!DOCTYPE html>
<html lang="en-us">
  <head>

    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    
<meta charset="UTF-8">
<title>Date histogram aggregation | Elasticsearch Guide [7.7] | Elastic</title>
<link rel="home" href="index.html" title="Elasticsearch Guide [7.7]">
<link rel="up" href="search-aggregations-bucket.html" title="Bucket Aggregations">
<link rel="prev" href="search-aggregations-bucket-composite-aggregation.html" title="Composite aggregation">
<link rel="next" href="search-aggregations-bucket-daterange-aggregation.html" title="Date Range Aggregation">
<meta name="DC.type" content="Learn/Docs/Elasticsearch/Reference/7.7">
<meta name="DC.subject" content="Elasticsearch">
<meta name="DC.identifier" content="7.7">
<meta name="robots" content="noindex,nofollow">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="https://cdn.optimizely.com/js/18132920325.js"></script>
    <link rel="apple-touch-icon" sizes="57x57" href="/apple-icon-57x57.png">
    <link rel="apple-touch-icon" sizes="60x60" href="/apple-icon-60x60.png">
    <link rel="apple-touch-icon" sizes="72x72" href="/apple-icon-72x72.png">
    <link rel="apple-touch-icon" sizes="76x76" href="/apple-icon-76x76.png">
    <link rel="apple-touch-icon" sizes="114x114" href="/apple-icon-114x114.png">
    <link rel="apple-touch-icon" sizes="120x120" href="/apple-icon-120x120.png">
    <link rel="apple-touch-icon" sizes="144x144" href="/apple-icon-144x144.png">
    <link rel="apple-touch-icon" sizes="152x152" href="/apple-icon-152x152.png">
    <link rel="apple-touch-icon" sizes="180x180" href="/apple-icon-180x180.png">
    <link rel="icon" type="image/png" href="/favicon-32x32.png" sizes="32x32">
    <link rel="icon" type="image/png" href="/android-chrome-192x192.png" sizes="192x192">
    <link rel="icon" type="image/png" href="/favicon-96x96.png" sizes="96x96">
    <link rel="icon" type="image/png" href="/favicon-16x16.png" sizes="16x16">
    <link rel="manifest" href="/manifest.json">
    <meta name="apple-mobile-web-app-title" content="Elastic">
    <meta name="application-name" content="Elastic">
    <meta name="msapplication-TileColor" content="#ffffff">
    <meta name="msapplication-TileImage" content="/mstile-144x144.png">
    <meta name="theme-color" content="#ffffff">
    <meta name="naver-site-verification" content="936882c1853b701b3cef3721758d80535413dbfd">
    <meta name="yandex-verification" content="d8a47e95d0972434">
    <meta name="localized" content="true">
    <meta name="st:robots" content="follow,index">
    <meta property="og:image" content="https://www.elastic.co/static/images/elastic-logo-200.png">
    <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon">
    <link rel="icon" href="/favicon.ico" type="image/x-icon">
    <link rel="apple-touch-icon-precomposed" sizes="64x64" href="/favicon_64x64_16bit.png">
    <link rel="apple-touch-icon-precomposed" sizes="32x32" href="/favicon_32x32.png">
    <link rel="apple-touch-icon-precomposed" sizes="16x16" href="/favicon_16x16.png">
    <!-- Give IE8 a fighting chance -->
    <!--[if lt IE 9]>
    <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
    <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
    <link rel="stylesheet" type="text/css" href="/guide/static/styles.css">
  </head>

  <!--© 2015-2021 Elasticsearch B.V. Copying, publishing and/or distributing without written permission is strictly prohibited.-->

  <body>
    <!-- Google Tag Manager -->
    <script>dataLayer = [];</script><noscript><iframe src="//www.googletagmanager.com/ns.html?id=GTM-58RLH5" height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
    <script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0], j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src= '//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f); })(window,document,'script','dataLayer','GTM-58RLH5');</script>
    <!-- End Google Tag Manager -->

    <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=UA-12395217-16"></script>
    <script>
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());
      gtag('config', 'UA-12395217-16');
    </script>

    <!--BEGIN QUALTRICS WEBSITE FEEDBACK SNIPPET-->
    <script type="text/javascript">
      (function(){var g=function(e,h,f,g){
      this.get=function(a){for(var a=a+"=",c=document.cookie.split(";"),b=0,e=c.length;b<e;b++){for(var d=c[b];" "==d.charAt(0);)d=d.substring(1,d.length);if(0==d.indexOf(a))return d.substring(a.length,d.length)}return null};
      this.set=function(a,c){var b="",b=new Date;b.setTime(b.getTime()+6048E5);b="; expires="+b.toGMTString();document.cookie=a+"="+c+b+"; path=/; "};
      this.check=function(){var a=this.get(f);if(a)a=a.split(":");else if(100!=e)"v"==h&&(e=Math.random()>=e/100?0:100),a=[h,e,0],this.set(f,a.join(":"));else return!0;var c=a[1];if(100==c)return!0;switch(a[0]){case "v":return!1;case "r":return c=a[2]%Math.floor(100/c),a[2]++,this.set(f,a.join(":")),!c}return!0};
      this.go=function(){if(this.check()){var a=document.createElement("script");a.type="text/javascript";a.src=g;document.body&&document.body.appendChild(a)}};
      this.start=function(){var a=this;window.addEventListener?window.addEventListener("load",function(){a.go()},!1):window.attachEvent&&window.attachEvent("onload",function(){a.go()})}};
      try{(new g(100,"r","QSI_S_ZN_emkP0oSe9Qrn7kF","https://znemkp0ose9qrn7kf-elastic.siteintercept.qualtrics.com/WRSiteInterceptEngine/?Q_ZID=ZN_emkP0oSe9Qrn7kF")).start()}catch(i){}})();
    </script><div id="ZN_emkP0oSe9Qrn7kF"><!--DO NOT REMOVE-CONTENTS PLACED HERE--></div>
    <!--END WEBSITE FEEDBACK SNIPPET-->

    <div id="elastic-nav" style="display:none;"></div>
    <script src="https://www.elastic.co/elastic-nav.js"></script>

    <!-- Subnav -->
    <div>
      <div>
        <div class="tertiary-nav d-none d-md-block">
          <div class="container">
            <div class="p-t-b-15 d-flex justify-content-between nav-container">
              <div class="breadcrum-wrapper"><span><a href="/guide/" style="font-size: 14px; font-weight: 600; color: #000;">Docs</a></span></div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="main-container">
      <section id="content">
        <div class="content-wrapper">

          <section id="guide" lang="en">
            <div class="container">
              <div class="row">
                <div class="col-xs-12 col-sm-8 col-md-8 guide-section">
                  <!-- start body -->
                  <div class="page_header">
<strong>IMPORTANT</strong>: No additional bug fixes or documentation updates
will be released for this version. For the latest information, see the
<a href="../current/index.html">current release documentation</a>.
</div>
<div id="content">
<div class="breadcrumbs">
<span class="breadcrumb-link"><a href="index.html">Elasticsearch Guide [7.7]</a></span>
»
<span class="breadcrumb-link"><a href="search-aggregations.html">Aggregations</a></span>
»
<span class="breadcrumb-link"><a href="search-aggregations-bucket.html">Bucket Aggregations</a></span>
»
<span class="breadcrumb-node">Date histogram aggregation</span>
</div>
<div class="navheader">
<span class="prev">
<a href="search-aggregations-bucket-composite-aggregation.html">« Composite aggregation</a>
</span>
<span class="next">
<a href="search-aggregations-bucket-daterange-aggregation.html">Date Range Aggregation »</a>
</span>
</div>
<div class="section">
<div class="titlepage"><div><div>
<h2 class="title">
<a id="search-aggregations-bucket-datehistogram-aggregation"></a>Date histogram aggregation<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/aggregations/bucket/datehistogram-aggregation.asciidoc">edit</a>
</h2>
</div></div></div>
<p>This multi-bucket aggregation is similar to the normal
<a class="xref" href="search-aggregations-bucket-histogram-aggregation.html" title="Histogram Aggregation">histogram</a>, but it can
only be used with date or date range values. Because dates are represented internally in
Elasticsearch as long values, it is possible, but not as accurate, to use the
normal <code class="literal">histogram</code> on dates as well. The main difference in the two APIs is
that here the interval can be specified using date/time expressions. Time-based
data requires special support because time-based intervals are not always a
fixed length.</p>
<div class="section">
<div class="titlepage"><div><div>
<h3 class="title">
<a id="calendar_and_fixed_intervals"></a>Calendar and fixed intervals<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/aggregations/bucket/datehistogram-aggregation.asciidoc">edit</a>
</h3>
</div></div></div>
<p>When configuring a date histogram aggregation, the interval can be specified
in two manners: calendar-aware time intervals, and fixed time intervals.</p>
<p>Calendar-aware intervals understand that daylight savings changes the length
of specific days, months have different amounts of days, and leap seconds can
be tacked onto a particular year.</p>
<p>Fixed intervals are, by contrast, always multiples of SI units and do not change
based on calendaring context.</p>
<div class="note admon">
<div class="icon"></div>
<div class="admon_content">
<h3>Combined <code class="literal">interval</code> field is deprecated</h3>
<p><span class="Admonishment Admonishment--change">
[<span class="Admonishment-version u-mono u-strikethrough">7.2</span>]
<span class="Admonishment-detail">
Deprecated in 7.2. <code class="literal">interval</code> field is deprecated
</span>
</span> Historically both calendar and fixed
intervals were configured in a single <code class="literal">interval</code> field, which led to confusing
semantics. Specifying <code class="literal">1d</code> would be assumed as a calendar-aware time,
whereas <code class="literal">2d</code> would be interpreted as fixed time. To get "one day" of fixed time,
the user would need to specify the next smaller unit (in this case, <code class="literal">24h</code>).</p>
<p>This combined behavior was often unknown to users, and even when knowledgeable about
the behavior it was difficult to use and confusing.</p>
<p>This behavior has been deprecated in favor of two new, explicit fields: <code class="literal">calendar_interval</code>
and <code class="literal">fixed_interval</code>.</p>
<p>By forcing a choice between calendar and intervals up front, the semantics of the interval
are clear to the user immediately and there is no ambiguity.  The old <code class="literal">interval</code> field
will be removed in the future.</p>
</div>
</div>
<div class="section">
<div class="titlepage"><div><div>
<h4 class="title">
<a id="calendar_intervals"></a>Calendar intervals<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/aggregations/bucket/datehistogram-aggregation.asciidoc">edit</a>
</h4>
</div></div></div>
<p>Calendar-aware intervals are configured with the <code class="literal">calendar_interval</code> parameter.
Calendar intervals can only be specified in "singular" quantities of the unit
(<code class="literal">1d</code>, <code class="literal">1M</code>, etc). Multiples, such as <code class="literal">2d</code>, are not supported and will throw an exception.</p>
<p>The accepted units for calendar intervals are:</p>
<div class="variablelist">
<dl class="variablelist">
<dt>
<span class="term">
minute (<code class="literal">1m</code>)
</span>
</dt>
<dd>
All minutes begin at 00 seconds.
One minute is the interval between 00 seconds of the first minute and 00
seconds of the following minute in the specified timezone, compensating for any
intervening leap seconds, so that the number of minutes and seconds past the
hour is the same at the start and end.
</dd>
<dt>
<span class="term">
hour (<code class="literal">1h</code>)
</span>
</dt>
<dd>
All hours begin at 00 minutes and 00 seconds.
One hour (1h) is the interval between 00:00 minutes of the first hour and 00:00
minutes of the following hour in the specified timezone, compensating for any
intervening leap seconds, so that the number of minutes and seconds past the hour
is the same at the start and end.
</dd>
<dt>
<span class="term">
day (<code class="literal">1d</code>)
</span>
</dt>
<dd>
All days begin at the earliest possible time, which is usually 00:00:00
(midnight).
One day (1d) is the interval between the start of the day and the start of
of the following day in the specified timezone, compensating for any intervening
time changes.
</dd>
<dt>
<span class="term">
week (<code class="literal">1w</code>)
</span>
</dt>
<dd>
One week is the interval between the start day_of_week:hour:minute:second
and the same day of the week and time of the following week in the specified
timezone.
</dd>
<dt>
<span class="term">
month (<code class="literal">1M</code>)
</span>
</dt>
<dd>
One month is the interval between the start day of the month and time of
day and the same day of the month and time of the following month in the specified
timezone, so that the day of the month and time of day are the same at the start
and end.
</dd>
<dt>
<span class="term">
quarter (<code class="literal">1q</code>)
</span>
</dt>
<dd>
One quarter (1q) is the interval between the start day of the month and
time of day and the same day of the month and time of day three months later,
so that the day of the month and time of day are the same at the start and end.<br>
</dd>
<dt>
<span class="term">
year (<code class="literal">1y</code>)
</span>
</dt>
<dd>
One year (1y) is the interval between the start day of the month and time of
day and the same day of the month and time of day the following year in the
specified timezone, so that the date and time are the same at the start and end.<br>
</dd>
</dl>
</div>
</div>

<div class="section">
<div class="titlepage"><div><div>
<h4 class="title">
<a id="calendar_interval_examples"></a>Calendar interval examples<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/aggregations/bucket/datehistogram-aggregation.asciidoc">edit</a>
</h4>
</div></div></div>
<p>As an example, here is an aggregation requesting bucket intervals of a month in calendar time:</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">POST /sales/_search?size=0
{
    "aggs" : {
        "sales_over_time" : {
            "date_histogram" : {
                "field" : "date",
                "calendar_interval" : "month"
            }
        }
    }
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/441.console"></div>
<p>If you attempt to use multiples of calendar units, the aggregation will fail because only
singular calendar units are supported:</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">POST /sales/_search?size=0
{
    "aggs" : {
        "sales_over_time" : {
            "date_histogram" : {
                "field" : "date",
                "calendar_interval" : "2d"
            }
        }
    }
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/442.console"></div>
<div class="pre_wrapper lang-js">
<pre class="programlisting prettyprint lang-js">{
  "error" : {
    "root_cause" : [...],
    "type" : "x_content_parse_exception",
    "reason" : "[1:82] [date_histogram] failed to parse field [calendar_interval]",
    "caused_by" : {
      "type" : "illegal_argument_exception",
      "reason" : "The supplied interval [2d] could not be parsed as a calendar interval.",
      "stack_trace" : "java.lang.IllegalArgumentException: The supplied interval [2d] could not be parsed as a calendar interval."
    }
  }
}</pre>
</div>
</div>

<div class="section">
<div class="titlepage"><div><div>
<h4 class="title">
<a id="fixed_intervals"></a>Fixed intervals<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/aggregations/bucket/datehistogram-aggregation.asciidoc">edit</a>
</h4>
</div></div></div>
<p>Fixed intervals are configured with the <code class="literal">fixed_interval</code> parameter.</p>
<p>In contrast to calendar-aware intervals, fixed intervals are a fixed number of SI
units and never deviate, regardless of where they fall on the calendar. One second
is always composed of 1000ms. This allows fixed intervals to be specified in
any multiple of the supported units.</p>
<p>However, it means fixed intervals cannot express other units such as months,
since the duration of a month is not a fixed quantity. Attempting to specify
a calendar interval like month or quarter will throw an exception.</p>
<p>The accepted units for fixed intervals are:</p>
<div class="variablelist">
<dl class="variablelist">
<dt>
<span class="term">
milliseconds (ms)
</span>
</dt>
<dt>
<span class="term">
seconds (s)
</span>
</dt>
<dd>
Defined as 1000 milliseconds each
</dd>
<dt>
<span class="term">
minutes (m)
</span>
</dt>
<dd>
All minutes begin at 00 seconds.
Defined as 60 seconds each (60,000 milliseconds)
</dd>
<dt>
<span class="term">
hours (h)
</span>
</dt>
<dd>
All hours begin at 00 minutes and 00 seconds.
Defined as 60 minutes each (3,600,000 milliseconds)
</dd>
<dt>
<span class="term">
days (d)
</span>
</dt>
<dd>
All days begin at the earliest possible time, which is usually 00:00:00
(midnight).
Defined as 24 hours (86,400,000 milliseconds)
</dd>
</dl>
</div>
</div>

<div class="section">
<div class="titlepage"><div><div>
<h4 class="title">
<a id="fixed_interval_examples"></a>Fixed interval examples<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/aggregations/bucket/datehistogram-aggregation.asciidoc">edit</a>
</h4>
</div></div></div>
<p>If we try to recreate the "month" <code class="literal">calendar_interval</code> from earlier, we can approximate that with
30 fixed days:</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">POST /sales/_search?size=0
{
    "aggs" : {
        "sales_over_time" : {
            "date_histogram" : {
                "field" : "date",
                "fixed_interval" : "30d"
            }
        }
    }
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/443.console"></div>
<p>But if we try to use a calendar unit that is not supported, such as weeks, we’ll get an exception:</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">POST /sales/_search?size=0
{
    "aggs" : {
        "sales_over_time" : {
            "date_histogram" : {
                "field" : "date",
                "fixed_interval" : "2w"
            }
        }
    }
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/444.console"></div>
<div class="pre_wrapper lang-js">
<pre class="programlisting prettyprint lang-js">{
  "error" : {
    "root_cause" : [...],
    "type" : "x_content_parse_exception",
    "reason" : "[1:82] [date_histogram] failed to parse field [fixed_interval]",
    "caused_by" : {
      "type" : "illegal_argument_exception",
      "reason" : "failed to parse setting [date_histogram.fixedInterval] with value [2w] as a time value: unit is missing or unrecognized",
      "stack_trace" : "java.lang.IllegalArgumentException: failed to parse setting [date_histogram.fixedInterval] with value [2w] as a time value: unit is missing or unrecognized"
    }
  }
}</pre>
</div>
</div>

<div class="section">
<div class="titlepage"><div><div>
<h4 class="title">
<a id="_notes_8"></a>Notes<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/aggregations/bucket/datehistogram-aggregation.asciidoc">edit</a>
</h4>
</div></div></div>
<p>In all cases, when the specified end time does not exist, the actual end time is
the closest available time after the specified end.</p>
<p>Widely distributed applications must also consider vagaries such as countries that
start and stop daylight savings time at 12:01 A.M., so end up with one minute of
Sunday followed by an additional 59 minutes of Saturday once a year, and countries
that decide to move across the international date line. Situations like
that can make irregular timezone offsets seem easy.</p>
<p>As always, rigorous testing, especially around time-change events, will ensure
that your time interval specification is
what you intend it to be.</p>
<p>WARNING:
To avoid unexpected results, all connected servers and clients must sync to a
reliable network time service.</p>
<div class="note admon">
<div class="icon"></div>
<div class="admon_content">
<p>fractional time values are not supported, but you can address this by
shifting to another time unit (e.g., <code class="literal">1.5h</code> could instead be specified as <code class="literal">90m</code>).</p>
</div>
</div>
<div class="note admon">
<div class="icon"></div>
<div class="admon_content">
<p>You can also specify time values using abbreviations supported by
<a class="xref" href="common-options.html#time-units" title="Time units">time units</a> parsing.</p>
</div>
</div>
</div>

<div class="section">
<div class="titlepage"><div><div>
<h4 class="title">
<a id="_keys_2"></a>Keys<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/aggregations/bucket/datehistogram-aggregation.asciidoc">edit</a>
</h4>
</div></div></div>
<p>Internally, a date is represented as a 64 bit number representing a timestamp
in milliseconds-since-the-epoch (01/01/1970 midnight UTC). These timestamps are
returned as the <code class="literal">key</code> name of the bucket. The <code class="literal">key_as_string</code> is the same
timestamp converted to a formatted
date string using the <code class="literal">format</code> parameter specification:</p>
<div class="tip admon">
<div class="icon"></div>
<div class="admon_content">
<p>If you don’t specify <code class="literal">format</code>, the first date
<a class="xref" href="mapping-date-format.html" title="format">format</a> specified in the field mapping is used.</p>
</div>
</div>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">POST /sales/_search?size=0
{
    "aggs" : {
        "sales_over_time" : {
            "date_histogram" : {
                "field" : "date",
                "calendar_interval" : "1M",
                "format" : "yyyy-MM-dd" <a id="CO220-1"></a><i class="conum" data-value="1"></i>
            }
        }
    }
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/445.console"></div>
<div class="calloutlist">
<table border="0" summary="Callout list">
<tr>
<td align="left" valign="top" width="5%">
<p><a href="#CO220-1"><i class="conum" data-value="1"></i></a></p>
</td>
<td align="left" valign="top">
<p>Supports expressive date <a class="xref" href="search-aggregations-bucket-daterange-aggregation.html#date-format-pattern" title="Date Format/Pattern">format pattern</a></p>
</td>
</tr>
</table>
</div>
<p>Response:</p>
<div class="pre_wrapper lang-console-result">
<pre class="programlisting prettyprint lang-console-result">{
    ...
    "aggregations": {
        "sales_over_time": {
            "buckets": [
                {
                    "key_as_string": "2015-01-01",
                    "key": 1420070400000,
                    "doc_count": 3
                },
                {
                    "key_as_string": "2015-02-01",
                    "key": 1422748800000,
                    "doc_count": 2
                },
                {
                    "key_as_string": "2015-03-01",
                    "key": 1425168000000,
                    "doc_count": 2
                }
            ]
        }
    }
}</pre>
</div>
</div>

<div class="section">
<div class="titlepage"><div><div>
<h4 class="title">
<a id="_timezone"></a>Timezone<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/aggregations/bucket/datehistogram-aggregation.asciidoc">edit</a>
</h4>
</div></div></div>
<p>Date-times are stored in Elasticsearch in UTC.  By default, all bucketing and
rounding is also done in UTC. Use the <code class="literal">time_zone</code> parameter to indicate
that bucketing should use a different timezone.</p>
<p>You can specify timezones as either an ISO 8601 UTC offset (e.g. <code class="literal">+01:00</code> or
<code class="literal">-08:00</code>)  or as a timezone ID as specified in the IANA timezone database,
such as`America/Los_Angeles`.</p>
<p>Consider the following example:</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">PUT my_index/_doc/1?refresh
{
  "date": "2015-10-01T00:30:00Z"
}

PUT my_index/_doc/2?refresh
{
  "date": "2015-10-01T01:30:00Z"
}

GET my_index/_search?size=0
{
  "aggs": {
    "by_day": {
      "date_histogram": {
        "field":     "date",
        "calendar_interval":  "day"
      }
    }
  }
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/446.console"></div>
<p>If you don’t specify a timezone, UTC is used. This would result in both of these
documents being placed into the same day bucket, which starts at midnight UTC
on 1 October 2015:</p>
<div class="pre_wrapper lang-console-result">
<pre class="programlisting prettyprint lang-console-result">{
  ...
  "aggregations": {
    "by_day": {
      "buckets": [
        {
          "key_as_string": "2015-10-01T00:00:00.000Z",
          "key":           1443657600000,
          "doc_count":     2
        }
      ]
    }
  }
}</pre>
</div>
<p>If you specify a <code class="literal">time_zone</code> of <code class="literal">-01:00</code>, midnight in that timezone is one hour
before midnight UTC:</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">GET my_index/_search?size=0
{
  "aggs": {
    "by_day": {
      "date_histogram": {
        "field":     "date",
        "calendar_interval":  "day",
        "time_zone": "-01:00"
      }
    }
  }
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/447.console"></div>
<p>Now the first document falls into the bucket for 30 September 2015, while the
second document falls into the bucket for 1 October 2015:</p>
<div class="pre_wrapper lang-console-result">
<pre class="programlisting prettyprint lang-console-result">{
  ...
  "aggregations": {
    "by_day": {
      "buckets": [
        {
          "key_as_string": "2015-09-30T00:00:00.000-01:00", <a id="CO221-1"></a><i class="conum" data-value="1"></i>
          "key": 1443574800000,
          "doc_count": 1
        },
        {
          "key_as_string": "2015-10-01T00:00:00.000-01:00", <a id="CO221-2"></a><i class="conum" data-value="1"></i>
          "key": 1443661200000,
          "doc_count": 1
        }
      ]
    }
  }
}</pre>
</div>
<div class="calloutlist">
<table border="0" summary="Callout list">
<tr>
<td align="left" valign="top" width="5%">
<p><a href="#CO221-1"><i class="conum" data-value="1"></i></a><a href="#CO221-2"></a></p>
</td>
<td align="left" valign="top">
<p>The <code class="literal">key_as_string</code> value represents midnight on each day
in the specified timezone.</p>
</td>
</tr>
</table>
</div>
<div class="warning admon">
<div class="icon"></div>
<div class="admon_content">
<p>When using time zones that follow DST (daylight savings time) changes,
buckets close to the moment when those changes happen can have slightly different
sizes than you would expect from the used <code class="literal">interval</code>.
For example, consider a DST start in the <code class="literal">CET</code> time zone: on 27 March 2016 at 2am,
clocks were turned forward 1 hour to 3am local time. If you use <code class="literal">day</code> as <code class="literal">interval</code>,
the bucket covering that day will only hold data for 23 hours instead of the usual
24 hours for other buckets. The same is true for shorter intervals, like 12h,
where you’ll have only a 11h bucket on the morning of 27 March when the DST shift
happens.</p>
</div>
</div>
</div>

<div class="section">
<div class="titlepage"><div><div>
<h4 class="title">
<a id="search-aggregations-bucket-datehistogram-offset"></a>Offset<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/aggregations/bucket/datehistogram-aggregation.asciidoc">edit</a>
</h4>
</div></div></div>
<p>Use the <code class="literal">offset</code> parameter to change the start value of each bucket by the
specified positive (<code class="literal">+</code>) or negative offset (<code class="literal">-</code>) duration, such as <code class="literal">1h</code> for
an hour, or <code class="literal">1d</code> for a day. See <a class="xref" href="common-options.html#time-units" title="Time units">Time units</a> for more possible time
duration options.</p>
<p>For example, when using an interval of <code class="literal">day</code>, each bucket runs from midnight
to midnight. Setting the <code class="literal">offset</code> parameter to <code class="literal">+6h</code> changes each bucket
to run from 6am to 6am:</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">PUT my_index/_doc/1?refresh
{
  "date": "2015-10-01T05:30:00Z"
}

PUT my_index/_doc/2?refresh
{
  "date": "2015-10-01T06:30:00Z"
}

GET my_index/_search?size=0
{
  "aggs": {
    "by_day": {
      "date_histogram": {
        "field":     "date",
        "calendar_interval":  "day",
        "offset":    "+6h"
      }
    }
  }
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/448.console"></div>
<p>Instead of a single bucket starting at midnight, the above request groups the
documents into buckets starting at 6am:</p>
<div class="pre_wrapper lang-console-result">
<pre class="programlisting prettyprint lang-console-result">{
  ...
  "aggregations": {
    "by_day": {
      "buckets": [
        {
          "key_as_string": "2015-09-30T06:00:00.000Z",
          "key": 1443592800000,
          "doc_count": 1
        },
        {
          "key_as_string": "2015-10-01T06:00:00.000Z",
          "key": 1443679200000,
          "doc_count": 1
        }
      ]
    }
  }
}</pre>
</div>
<div class="note admon">
<div class="icon"></div>
<div class="admon_content">
<p>The start <code class="literal">offset</code> of each bucket is calculated after <code class="literal">time_zone</code>
adjustments have been made.</p>
</div>
</div>
</div>

<div class="section">
<div class="titlepage"><div><div>
<h4 class="title">
<a id="_keyed_response_3"></a>Keyed Response<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/aggregations/bucket/datehistogram-aggregation.asciidoc">edit</a>
</h4>
</div></div></div>
<p>Setting the <code class="literal">keyed</code> flag to <code class="literal">true</code> associates a unique string key with each
bucket and returns the ranges as a hash rather than an array:</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">POST /sales/_search?size=0
{
    "aggs" : {
        "sales_over_time" : {
            "date_histogram" : {
                "field" : "date",
                "calendar_interval" : "1M",
                "format" : "yyyy-MM-dd",
                "keyed": true
            }
        }
    }
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/449.console"></div>
<p>Response:</p>
<div class="pre_wrapper lang-console-result">
<pre class="programlisting prettyprint lang-console-result">{
    ...
    "aggregations": {
        "sales_over_time": {
            "buckets": {
                "2015-01-01": {
                    "key_as_string": "2015-01-01",
                    "key": 1420070400000,
                    "doc_count": 3
                },
                "2015-02-01": {
                    "key_as_string": "2015-02-01",
                    "key": 1422748800000,
                    "doc_count": 2
                },
                "2015-03-01": {
                    "key_as_string": "2015-03-01",
                    "key": 1425168000000,
                    "doc_count": 2
                }
            }
        }
    }
}</pre>
</div>
</div>

<div class="section">
<div class="titlepage"><div><div>
<h4 class="title">
<a id="_scripts_2"></a>Scripts<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/aggregations/bucket/datehistogram-aggregation.asciidoc">edit</a>
</h4>
</div></div></div>
<p>As with the normal <a class="xref" href="search-aggregations-bucket-histogram-aggregation.html" title="Histogram Aggregation">histogram</a>,
both document-level scripts and
value-level scripts are supported. You can control the order of the returned
buckets using the <code class="literal">order</code>
settings and filter the returned buckets based on a <code class="literal">min_doc_count</code> setting
(by default all buckets between the first
bucket that matches documents and the last one are returned). This histogram
also supports the <code class="literal">extended_bounds</code>
setting, which enables extending the bounds of the histogram beyond the data
itself. For more information, see
<a class="xref" href="search-aggregations-bucket-histogram-aggregation.html#search-aggregations-bucket-histogram-aggregation-extended-bounds"><code class="literal">Extended Bounds</code></a>.</p>
</div>

<div class="section">
<div class="titlepage"><div><div>
<h4 class="title">
<a id="_missing_value_14"></a>Missing value<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/aggregations/bucket/datehistogram-aggregation.asciidoc">edit</a>
</h4>
</div></div></div>
<p>The <code class="literal">missing</code> parameter defines how to treat documents that are missing a value.
By default, they are ignored, but it is also possible to treat them as if they
have a value.</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">POST /sales/_search?size=0
{
    "aggs" : {
        "sale_date" : {
             "date_histogram" : {
                 "field" : "date",
                 "calendar_interval": "year",
                 "missing": "2000/01/01" <a id="CO222-1"></a><i class="conum" data-value="1"></i>
             }
         }
    }
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/450.console"></div>
<div class="calloutlist">
<table border="0" summary="Callout list">
<tr>
<td align="left" valign="top" width="5%">
<p><a href="#CO222-1"><i class="conum" data-value="1"></i></a></p>
</td>
<td align="left" valign="top">
<p>Documents without a value in the <code class="literal">publish_date</code> field will fall into the
same bucket as documents that have the value <code class="literal">2000-01-01</code>.</p>
</td>
</tr>
</table>
</div>
</div>

<div class="section">
<div class="titlepage"><div><div>
<h4 class="title">
<a id="_order_2"></a>Order<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/aggregations/bucket/datehistogram-aggregation.asciidoc">edit</a>
</h4>
</div></div></div>
<p>By default the returned buckets are sorted by their <code class="literal">key</code> ascending, but you can
control the order using
the <code class="literal">order</code> setting. This setting supports the same <code class="literal">order</code> functionality as
<a class="xref" href="search-aggregations-bucket-terms-aggregation.html#search-aggregations-bucket-terms-aggregation-order" title="Order"><code class="literal">Terms Aggregation</code></a>.</p>
</div>

<div class="section">
<div class="titlepage"><div><div>
<h4 class="title">
<a id="_using_a_script_to_aggregate_by_day_of_the_week"></a>Using a script to aggregate by day of the week<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/aggregations/bucket/datehistogram-aggregation.asciidoc">edit</a>
</h4>
</div></div></div>
<p>When you need to aggregate the results by day of the week, use a script that
returns the day of the week:</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">POST /sales/_search?size=0
{
    "aggs": {
        "dayOfWeek": {
            "terms": {
                "script": {
                    "lang": "painless",
                    "source": "doc['date'].value.dayOfWeekEnum.value"
                }
            }
        }
    }
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/451.console"></div>
<p>Response:</p>
<div class="pre_wrapper lang-console-result">
<pre class="programlisting prettyprint lang-console-result">{
  ...
  "aggregations": {
    "dayOfWeek": {
      "doc_count_error_upper_bound": 0,
      "sum_other_doc_count": 0,
      "buckets": [
        {
          "key": "7",
          "doc_count": 4
        },
        {
          "key": "4",
          "doc_count": 3
        }
      ]
    }
  }
}</pre>
</div>
<p>The response will contain all the buckets having the relative day of
the week as key : 1 for Monday, 2 for Tuesday…​ 7 for Sunday.</p>
</div>

</div>

</div>
<div class="navfooter">
<span class="prev">
<a href="search-aggregations-bucket-composite-aggregation.html">« Composite aggregation</a>
</span>
<span class="next">
<a href="search-aggregations-bucket-daterange-aggregation.html">Date Range Aggregation »</a>
</span>
</div>
</div>

                  <!-- end body -->
                </div>
                <div class="col-xs-12 col-sm-4 col-md-4" id="right_col">
                  <div id="rtpcontainer" style="display: block;">
                    <div class="mktg-promo">
                      <h3>Most Popular</h3>
                      <ul class="icons">
                        <li class="icon-elasticsearch-white"><a href="https://www.elastic.co/webinars/getting-started-elasticsearch?baymax=default&amp;elektra=docs&amp;storm=top-video">Get Started with Elasticsearch: Video</a></li>
                        <li class="icon-kibana-white"><a href="https://www.elastic.co/webinars/getting-started-kibana?baymax=default&amp;elektra=docs&amp;storm=top-video">Intro to Kibana: Video</a></li>
                        <li class="icon-logstash-white"><a href="https://www.elastic.co/webinars/introduction-elk-stack?baymax=default&amp;elektra=docs&amp;storm=top-video">ELK for Logs &amp; Metrics: Video</a></li>
                      </ul>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </section>

        </div>


<div id="elastic-footer"></div>
<script src="https://www.elastic.co/elastic-footer.js"></script>
<!-- Footer Section end-->

      </section>
    </div>

<script src="/guide/static/jquery.js"></script>
<script type="text/javascript" src="/guide/static/docs.js"></script>
<script type="text/javascript">
  window.initial_state = {}</script>
  </body>
</html>
